package org.zxb.demo.annotation;

import org.springframework.core.annotation.AliasFor;
import org.springframework.web.multipart.MultipartFile;
import org.zxb.demo.constant.FileType;
import org.zxb.demo.resolver.AbstractMultipartFileValidator;

import javax.annotation.Resource;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.constraints.DecimalMax;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author zxb
 */

@Inherited
@Target({PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {ExcelMultipartFileValidator.class})
public @interface ExcelMultipartFile {
    String message() default "文件校验失败";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 文件类型限制
     */
    @AliasFor(
            annotation = MultipartFileVerify.class
    )
    FileType[] value() default {};
}


/**
 * 单个 ExcelMultipartFile 校验
 */
class ExcelMultipartFileValidator implements ConstraintValidator<MultipartFileVerify, MultipartFile> {
    @Resource
    private AbstractMultipartFileValidator abstractMultipartFileValidator;

    private MultipartFileVerify multipartFileValid;

    @Override
    public void initialize(MultipartFileVerify constraintAnnotation) {
        this.multipartFileValid = constraintAnnotation;
    }

    @Override
    public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        return abstractMultipartFileValidator.isFileValid(multipartFileValid, value);
    }
}